import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:yyshort/common/apis/apis.dart';
import 'package:yyshort/common/model/record_model.dart';
import 'package:yyshort/common/model/video_model.dart';

import 'index.dart';

class RecordController extends GetxController {
  RecordController();

  final state = RecordState();

  /// UI 组件
  final RefreshController refreshController = RefreshController(
    initialRefresh: true,
  );

  int curPage = 1;
  int total = 10;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  void onRefresh() {
    fetchNewsList(isRefresh: true)
        .then((_) {

            refreshController.refreshCompleted(resetFooterState: true);
          
        })
        .catchError((_) {
          refreshController.refreshFailed();
        });
  }

  void onLoading() {
    fetchNewsList(isRefresh: false)
        .then((_) {
          if (state.record_modelList.length < total * curPage) {
            refreshController.loadNoData();
          } else {
            refreshController.loadComplete();
          }
        })
        .catchError((_) {
          refreshController.loadFailed();
        });
  }

  Future<void> fetchNewsList({bool isRefresh = false}) async {
    if (isRefresh == true) {
      curPage = 1;
      state.record_modelList.clear();
    } else {
      curPage++;
    }
    List<RecordModel> result = await UserAPI.asset_record(curPage);

    state.record_modelList.addAll(result);
    if (isRefresh == true && state.record_modelList.isEmpty) {
      state.isNeedShowEmpty = true;
    }
  }
}
